package com.eve.springcloud.lb;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

/**
 * 模仿Ribbon的轮询算法来手写轮询算法
 * @author HXL
 * 20200511
 */
@Component           // 表示加载模块
public class MyLB implements LoadBalancer {

	private AtomicInteger atomicInt = new AtomicInteger(0);
	/**
	 * 获取第几次访问
	 * @return
	 */
	public final int getAndIncrement() {
		int current;
		int next;
		do {
			current = this.atomicInt.get();
			next = current >= 2147483647 ? 0 : current + 1;      // 越界判断
		}while(this.atomicInt.compareAndSet(current, next)) ;
		System.out.println("***第几次访问，次数next:" + next);
		return next;
	}
	
	@Override
	public ServiceInstance instance(List<ServiceInstance> instances) {
		// 第几次访问的下标数
		int index = getAndIncrement() % instances.size();
		
		return instances.get(index);
	}

}
